import React, { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import AgentService from '@/modules/Agent';
import Network from '@/modules/Network';

const FloatAlert = (props: { visible: boolean; close: () => void }) => {
	const { t } = useTranslation();
	const canvasRef = useRef<HTMLCanvasElement | null>(null);

	useEffect(() => {
		createVideo()
	}, []);

	// export interface IAgentStatus {
	// 	logged: boolean; //登入
	// 	ready: boolean; //就绪
	// 	otherWork: boolean; //小休
	// 	checkIn: boolean; //签入
	// 	isChief: boolean;
	// 	afterWork: boolean;
	// }

	let isRed = true; // Flag to track current color
	let isDisconnect = false;

	const getAgentInfo = () => {
		// afterWork
		if (AgentService.agentStatus.afterWork) {
			return t('work-arrange');
		} else if (AgentService.sessionId && AgentService.sessionMembers?.length) {
			return t('calling');
		} else if (AgentService.sessionId && AgentService.sessionMembers?.length <= 0) {
			return t('ringing');
		} else if (AgentService.agentStatus.otherWork) {
			return t('short-break')
		} else if (AgentService.agentStatus.ready) {
			return t('ready-status')
		} else {
			return t('not-ready-status')
		}
	}

	const getAmsNetworkInfo = () => {
		if (isDisconnect) {
			// return t('disconnect-from-dispatch-system-relogin')
			return '您与坐席管理系统断开，请重新登录'
		}
		if (AgentService.amsNetworkTips) {
			return t(AgentService.amsNetworkTips)
		}
		return '正常'
	}

	const getWaitingInfo = () => {
		if (AgentService.agentStatus.ready || AgentService.agentStatus.checkIn) {
			return t('call-progress-total') + '：' + AgentService.callProgress
		} else {
			return ''
		}
	}

	const isRinging = () => {
		return AgentService.sessionId && AgentService.sessionMembers?.length <= 0
	}


	const getBackgroundColor = () => {
		// 'connected' | 'reconnect_failed' | 'reconnecting' | 'offline' | 'online' | 'ping-connected' | 'ping-timeout | 'error' | 'disconnect'
		// 网络在线背景绿色
		// 重连中背景黄色 disconnect-from-dispatch-system-reconnect 233，164，70
		// 掉线背景红色 disconnect-from-dispatch-system-relogin RGB(199,0,11)
		// 振铃：选择两个颜色交替，模拟闪烁效果 （红黄交替闪烁）
		if (!isDisconnect && ['disconnect', 'reconnect_failed'].includes(Network.amsStatus)) {
			isDisconnect = true;
		}
		if (isDisconnect) {
			return 'rgb(199, 0, 11)'
		} else if (Network.amsStatus === 'online' || Network.amsStatus === 'ping-connected') {
			isDisconnect = false;
			if (isRinging()) {
				isRed = !isRed;
				return isRed ? 'rgb(199, 0, 11)' : 'rgb(233, 164, 70)';
			}
			return 'green'
		} else if (Network.amsStatus === 'offline' || Network.amsStatus === 'reconnecting' || Network.amsStatus === 'ping-timeout' || Network.amsStatus === 'error') {
			return 'rgb(233, 164, 70)'
		} else {
			console.log('Network.amsStatus', Network.amsStatus);
			return 'green'
		}
	}

	const getFontColor = () => {
		if (isDisconnect) {
			return 'white'
		} else if (Network.amsStatus === 'online' || Network.amsStatus === 'ping-connected') {
			if (isRinging()) {
				return isRed ? 'white' : 'black';
			}
			return 'white'
		} else if (Network.amsStatus === 'offline' || Network.amsStatus === 'reconnecting' || Network.amsStatus === 'ping-timeout' || Network.amsStatus === 'error') {
			return 'black'
		} else {
			return 'white'
		}
	}

	useEffect(() => {
		if (props.visible && canvasRef.current) {
			const ctx = canvasRef.current.getContext('2d');

			function renderVideoFrame() {
				if (!ctx || !canvasRef.current) {
					return;
				}

				ctx.fillStyle = getBackgroundColor();
				ctx.fillRect(0, 0, canvasRef.current.width, canvasRef.current.height);
				
				// 在画布上绘制动态文字
				ctx.fillStyle = getFontColor();
				ctx.font = '12px Arial';
				ctx.textBaseline = 'top';
				ctx.textAlign = 'left';
				ctx.fillText('座席状态：' + getAgentInfo(), 20, 40);
				ctx.fillText('网络状态：' + getAmsNetworkInfo(), 20, 60);
				ctx.fillText(getWaitingInfo(), 20, 80);

				// 递归调用以持续渲染视频帧
				// requestAnimationFrame(renderVideoFrame);
				// Repeat the draw function every 500 milliseconds (0.5 seconds)
				setTimeout(renderVideoFrame, 200);
			}

			// 开始渲染视频帧
			renderVideoFrame();

			// 将画布内容捕获为 MediaStream，并将其赋值给 video 元素
			const video = createVideo()
			canvasRef.current
				.captureStream()
				.getVideoTracks()
				.forEach(track => {
					if (video) video.srcObject = new MediaStream([track]);
				});

			// 获取画中画按钮和视频元素
			video.onloadeddata = (event) => {
				video.play();
				video.requestPictureInPicture();
			  };

		} else {
			// 如果已经在画中画模式中，则退出画中画
			console.log('document.pictureInPictureElement', document.pictureInPictureElement);
			if (document.pictureInPictureElement) {
				document.exitPictureInPicture();
			  }
		}
		return () => {
			if (document.pictureInPictureElement) {
				document.exitPictureInPicture();
			  }
		};
	}, [props.visible]);

	const createVideo = () => {
		let video = document.getElementById('float-alert-video') as HTMLVideoElement;
		if (!video) {
			video = document.createElement('video') as HTMLVideoElement;
			video.id = 'float-alert-video'
			video.setAttribute('autoplay', '');
			video.setAttribute('playsinline', '');
			video.setAttribute('controls', 'true');
			video.setAttribute('mute', 'true');
			video.style.display = 'none';
			video.style.background = '#fff';
			video.width = 640;
			video.height = 360;
			video.autoplay = true;
			video.playsInline = true;
			video.disablePictureInPicture = false;
			document.body.appendChild(video);
			video.onleavepictureinpicture = (event) => { 
				console.log('onleavepictureinpicture', event);
				video.pause();
				video.srcObject = null;
				props.close && props.close() 
			};
		}
		return video;
	}

	return (
		<div>
			<canvas style={{ display: 'none', width: '640px', height: '360px' }} ref={canvasRef}></canvas>
			{/* <video style={{ display: 'none', width: '640px', height: '360px' }} ref={videoRef}></video> */}
		</div>
	);
};

export default FloatAlert;
